// 初始化图表
let heatGauge, changeDistribution, limitChart;
let limitUpData = [], yesterdayLimitUpData = [], failedLimitUpData = [];

// 标签页切换功能
function openTab(evt, tabName) {
    const tabContents = document.getElementsByClassName("tab-content");
    for (let i = 0; i < tabContents.length; i++) {
        tabContents[i].classList.remove("active");
    }

    const tabButtons = document.getElementsByClassName("tab-button");
    for (let i = 0; i < tabButtons.length; i++) {
        tabButtons[i].classList.remove("active");
    }

    document.getElementById(tabName).classList.add("active");
    evt.currentTarget.classList.add("active");
}

// 生成随机股票数据
function generateStockData(count) {
    const stocks = [];
    const prefixes = ['SH', 'SZ', 'BJ'];
    const names = ['茅台', '腾讯', '阿里', '平安', '宁德', '比亚迪', '美的', '格力', '万科', '中信'];
    
    for (let i = 0; i < count; i++) {
        const prefix = prefixes[Math.floor(Math.random() * prefixes.length)];
        const code = prefix + (600000 + Math.floor(Math.random() * 10000));
        const name = names[Math.floor(Math.random() * names.length)] + (Math.floor(Math.random() * 10) + 1);
        const price = (Math.random() * 100 + 10).toFixed(2);
        const change = (Math.random() * 20 - 10).toFixed(2);
        const pctChange = (Math.random() * 20 - 10).toFixed(2);
        
        stocks.push({
            code,
            name,
            price,
            change,
            pctChange
        });
    }
    return stocks;
}

// 初始化仪表图
function initHeatGauge() {
    const ctx = document.getElementById('heatGauge').getContext('2d');
    heatGauge = new Chart(ctx, {
        type: 'doughnut',
        data: {
            datasets: [{
                data: [100],
                backgroundColor: ['#52c41a'],
                borderWidth: 0
            }]
        },
        options: {
            circumference: 270,
            rotation: 225,
            cutout: '80%',
            plugins: {
                legend: { display: false },
                tooltip: { 
                    enabled: true,
                    callbacks: {
                        label: function(context) {
                            return getGaugeDescription(context.raw);
                        }
                    }
                }
            }
        },
        plugins: [{
            id: 'centerText',
            afterDraw: function(chart) {
                const width = chart.width;
                const height = chart.height;
                const ctx = chart.ctx;
                
                ctx.restore();
                const fontSize = (height / 5).toFixed(2);
                ctx.font = `bold ${fontSize}px Arial`;
                ctx.textBaseline = 'middle';
                ctx.textAlign = 'center';
                
                const text = chart.data.datasets[0].data[0];
                const textX = width / 2;
                const textY = height / 2 - 10;
                
                ctx.fillStyle = '#333';
                ctx.fillText(text, textX, textY);
                
                // 添加描述文字
                ctx.font = `14px Arial`;
                const desc = getGaugeDescription(text);
                ctx.fillText(desc, textX, textY + 55);
                ctx.save();
            }
        }]
    });
}

// 初始化涨跌分布图
function initChangeDistribution() {
    const ctx = document.getElementById('changeDistribution').getContext('2d');
    changeDistribution = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: Array.from({length: 23}, (_, i) => (i - 11)),
            datasets: [{
                data: Array(23).fill(0),
                backgroundColor: Array(23).fill(0).map((_, i) => 
                    i < 11 ? '#52c41a' : i === 11 ? '#d9d9d9' : '#f5222d'),
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: { display: false },
                title: {
                    display: true,
                    text: '涨跌分布'
                }
            },
            scales: {
                y: { 
                    beginAtZero: true,
                    display: true,
                    ticks: {
                        color: '#666',
                        font: {
                            size: 10
                        }
                    },
                    grid: {
                        color: 'rgba(0,0,0,0.05)'
                    }
                },
                x: { 
                    grid: { display: false },
                    ticks: {
                        color: '#666',
                        font: {
                            size: 10
                        }
                    }
                }
            }
        }
    });
}

// 初始化涨跌停曲线
function initLimitChart() {
    const ctx = document.getElementById('limitChart').getContext('2d');
    limitChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: Array.from({length: 60}, (_, i) => {
                const date = new Date();
                date.setMinutes(date.getMinutes() - (59 - i));
                return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
            }),
            datasets: [
                {
                    label: '涨停',
                    data: Array(60).fill(0),
                    borderColor: '#f5222d',
                    backgroundColor: 'rgba(245, 34, 45, 0.1)',
                    tension: 0.1,
                    fill: true
                },
                {
                    label: '跌停',
                    data: Array(60).fill(0),
                    borderColor: '#52c41a',
                    backgroundColor: 'rgba(82, 196, 26, 0.1)',
                    tension: 0.1,
                    fill: true
                }
            ]
        },
        options: {
            responsive: true,
            plugins: {
                title: {
                    display: true,
                    text: '涨跌停数量'
                }
            },
            scales: {
                y: { beginAtZero: true }
            }
        }
    });
}

// 更新表格数据
function updateTables() {
    limitUpData = generateStockData(10);
    yesterdayLimitUpData = generateStockData(10);
    failedLimitUpData = generateStockData(10);
    
    renderTable('limitUpTable', limitUpData);
    renderTable('yesterdayLimitUpTable', yesterdayLimitUpData);
    renderTable('failedLimitUpTable', failedLimitUpData);
}

// 渲染表格
function renderTable(tableId, data) {
    const table = document.getElementById(tableId);
    table.innerHTML = `
        <tr>
            <th>代码</th>
            <th>名称</th>
            <th>最新价</th>
            <th>涨跌幅</th>
        </tr>
    `;
    
    data.forEach(stock => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${stock.code}</td>
            <td>${stock.name}</td>
            <td>${stock.price}</td>
            <td style="color: ${stock.pctChange >= 0 ? '#f5222d' : '#52c41a'}">
                ${stock.pctChange >= 0 ? '+' : ''}${stock.pctChange}%
            </td>
        `;
        table.appendChild(row);
    });
}

// 更新所有图表数据
function updateCharts() {
    // 更新仪表图
    const heatValue = Math.floor(Math.random() * 101);
    heatGauge.data.datasets[0].data = [heatValue, 100 - heatValue];
    heatGauge.data.datasets[0].backgroundColor = [
        getGaugeColor(heatValue),
        '#f5f5f5'
    ];
    heatGauge.update();

    // 更新涨跌分布
    const distributionData = Array.from({length: 23}, () => Math.floor(Math.random() * 50));
    changeDistribution.data.datasets[0].data = distributionData;
    changeDistribution.update();

    // 更新涨跌停曲线
    limitChart.data.datasets[0].data.shift();
    limitChart.data.datasets[0].data.push(Math.floor(Math.random() * 50));
    limitChart.data.datasets[1].data.shift();
    limitChart.data.datasets[1].data.push(Math.floor(Math.random() * 30));
    limitChart.update();
}

// 获取仪表图颜色和描述
function getGaugeColor(value) {
    // 0-50: 绿色渐变 (#52c41a -> #237804)
    // 50-100: 红色渐变 (#f5222d -> #820014)
    if (value <= 10) return '#f6ffed';
    if (value <= 20) return '#d9f7be';
    if (value <= 30) return '#b7eb8f';
    if (value <= 40) return '#95de64';
    if (value <= 50) return '#73d13d';
    if (value <= 60) return '#ffccc7';
    if (value <= 70) return '#ffa39e';
    if (value <= 80) return '#ff7875';
    if (value <= 90) return '#ff4d4f';
    return '#cf1322';
}

function getGaugeDescription(value) {
    if (value < 20) return '市场冷淡，交易量低';
    if (value < 40) return '市场平稳，观望情绪浓厚';
    if (value < 60) return '市场活跃，交易量适中';
    if (value < 80) return '市场火热，交易活跃';
    return '市场过热，风险较高';
}

// 初始化所有图表和数据
function init() {
    initHeatGauge();
    initChangeDistribution();
    initLimitChart();
    updateTables();
    updateCharts();
    
    // 每5秒更新数据
    setInterval(() => {
        updateCharts();
        updateTables();
    }, 5000);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', init);
